const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
const {setBillNo, saveHistPrice, setInvoiceGoods} = require("../bill/base");
const tools = require("../../tools/tool");
const router = new Router();
// 提交购物车
router.post('/app/saveSale', async ctx => {
    try {
        let user = ctx.user;
        let uid = user.id;
        let tenantId = user.tenantId;
        let buId = ctx.request.body.buId;
        // let buName = ctx.request.body.buName;
        let billId = ctx.request.body.billId;
        let infos = ctx.request.body.infos;
        if(!buId) return ctx.err('没有选择客户')
        if(infos.length === 0) return ctx.err('没有选择商品')
        let salesId = uid;
        let cby = uid;
        let transType = 150601;
        let transTypeName = '销售单';
        let billType = 'SALE';
        let billState = 'draft';
        let createdAt = tool.getTime();
        let billDate = tool.getDay();
        let billNo =''
        let totalAmount = tool.xe.sum(infos, 'amount')
        let amount = tool.xe.sum(infos, 'amount')
        let subRemark = []
        let cartIds = []
        infos.map(row => {
            if(row.remark) subRemark.push(row.remark)
            if(row.id) {
                cartIds.push(row.id)
            }
        })
        let storage = await db.models['storage'].findOne({
            where: {
                tenantId,
                name: '默认仓库'
            }
        })
        if(!storage) return ctx.err('仓库设置错误')
        let invoice = null
        if(billId) {
            invoice = await db.models['invoice'].findOne({
                where: {
                    tenantId,
                    id: billId,
                }
            })
            billNo = invoice.billNo
            invoice.totalAmount = totalAmount
            invoice.amount = amount
            invoice.arrears = amount
            invoice.leftAmount = amount
            invoice.salesId = salesId
            invoice.updatedAt = tool.getTime()
            invoice.orgin = 'app'
        }
        else {
            billNo = await setBillNo(tenantId, 150601);
            invoice = db.models['invoice'].build()
            invoice.tenantId = tenantId
            invoice.printNo = 0
            invoice.billState = billState
            invoice.billNo = billNo
            invoice.billDate = billDate
            invoice.billType = billType
            invoice.transType = transType
            invoice.transTypeName = transTypeName
            invoice.totalAmount = totalAmount
            invoice.totalDiscount = 0
            invoice.disAmount = 0
            invoice.amount = amount
            invoice.ysAmount = 0
            invoice.rpAmount = 0
            invoice.arrears = amount
            invoice.hxAmount = 0
            invoice.yhAmount = 0
            invoice.leftAmount = amount
            invoice.buId = buId
            invoice.salesId = salesId
            invoice.subRemark = subRemark.length > 0 ?subRemark.join(','):''
            invoice.byCell = 1
            invoice.cby = cby
            invoice.createdAt = createdAt
            invoice.orgin = 'app'
        }
        let units = await tool.getUnits()
        for (let i = 0; i < infos.length; i++) {
            let row = infos[i]
            let qty = tool.xe.multiply(row.qty,row.calNum)
            if(qty.toString().indexOf('.') !== -1) {
                return ctx.err(`${row.invName} 最小单位数量不能为小数`)
            }
            units.map(unit => {
                if(unit.name === row.unit) {
                    row.unitId = unit.id
                }
            })
            row.price = tool.xe.toNumber(row.price)
            row.amount = tool.xe.multiply(row.qty, tool.xe.subtract(row.price, row.deduction))
            row.tenantId = tenantId
            row.locationId = storage.id
            row.locationName = storage.name
            row.billNo = billNo
            row.transType = transType
            row.buId = buId
            row.send = row.send?tool.xe.trim(row.send):''
            row.deduction = tool.xe.toNumber(row.deduction)
            row.remark = row.remark?tool.xe.trim(row.remark):''
            row.calNum = row.unit===row.unit1?row.spec:1
            if(invoice.transType === 150601) {
                if(!row.price) {
                    if(!row.send && !row.remark) {
                        return ctx.err('单价为 0 必须要有备注 或 选择赠品')
                    }
                }
            }
            if(!row.calNum) {
                return ctx.err('规格不正确')
            }
            row.assQty = tool.calAssQty(row.qty,row.spec,row.unit1, row.unit2)
        }

        let ret = await db.transaction(async () => {
            let invo = await invoice.save()
            if(invo) {
                infos.map(row => {
                    row.iid = invo.id
                    delete row.id
                })
            }
            if(billId) {
                await db.models['invoiceInfo'].destroy({
                    where: {
                        tenantId,
                        iid: billId
                    }
                })
            }
            await db.models['invoiceInfo'].bulkCreate(infos);
            await saveHistPrice(invo, infos)
            await setInvoiceGoods(tenantId, invo.id)

            let obj = Object.assign({}, invo)
            obj.infos = infos
            await tools.saveLogInvoice(tenantId, uid, invo.id, billId ?'修改':'新增', obj);

            if(cartIds.length > 0) {
                await db.query(`delete from cart where tenantId=${tenantId} and id in(${cartIds.join(',')}) `,{type: QueryTypes.DELETE})
            }
            return invo
        })
        if(ret) {
            // let roomId = ctx.roomId
            // if(roomId) {
            //     setTimeout(async () => {
            //         let msg = '新增 手机订单'
            //         if(billId) msg = '手机订单 ' + invoice.billNo + ' 被修改'
            //         ctx.io.to(roomId).emit('appBillAdd', msg)
            //     }, 300)
            // }
        }

        return ctx.suc('提交成功', ret)
    } catch (e) {
        return ctx.err(e)
    }
})
router.post('/app/editSale', async ctx => {
    try {
        let user = ctx.user;
        let uid = user.id;
        let tenantId = user.tenantId;
        let buId = ctx.request.body.buId;
        let id = ctx.request.body.id;
        let infos = ctx.request.body.infos;
        if(!buId) return ctx.err('没有选择客户')
        if(infos.length === 0) return ctx.err('没有选择商品')
        let salesId = uid;
        let totalAmount = tool.xe.sum(infos, 'amount')
        let amount = tool.xe.sum(infos, 'amount')

        let storage = await db.models['storage'].findOne({
            where: {
                tenantId,
                name: '默认仓库'
            }
        })
        if(!storage) return ctx.err('仓库设置错误')
        let invoice = null
        let units = await tool.getUnits()
        if(id) {
            invoice = await db.models['invoice'].findOne({
                where: {
                    tenantId,
                    id,
                }
            })
            invoice.totalAmount = totalAmount
            invoice.amount = amount
            invoice.arrears = amount
            invoice.leftAmount = amount
            invoice.salesId = salesId
            invoice.updatedAt = tool.getTime()
            invoice.orgin = 'app'
        }
        for (let i = 0; i < infos.length; i++) {
            let row = infos[i]
            let qty = tool.xe.multiply(row.qty,row.calNum)
            if(qty.toString().indexOf('.') !== -1) {
                return ctx.err(`${row.invName} 最小单位数量不能为小数`)
            }
            units.map(unit => {
                if(unit.name === row.unit) {
                    row.unitId = unit.id
                }
            })
            row.price = tool.xe.toNumber(row.price)
            row.amount = tool.xe.multiply(row.qty, tool.xe.subtract(row.price, row.deduction))
            row.tenantId = tenantId
            row.locationId = storage.id
            row.locationName = storage.name
            row.billNo = invoice.billNo
            row.buId = buId
            row.send = row.send?tool.xe.trim(row.send):''
            row.deduction = tool.xe.toNumber(row.deduction)
            row.remark = row.remark?tool.xe.trim(row.remark):''
            row.calNum = row.unit===row.unit1?row.spec:1
            if(invoice.transType === 150601) {
                if(!row.price) {
                    if(!row.send && !row.remark) {
                        return ctx.err('单价为 0 必须要有备注 或 选择赠品')
                    }
                }
            }
            if(!row.calNum) {
                return ctx.err('规格不正确')
            }
            row.assQty = tool.calAssQty(row.qty,row.spec,row.unit1, row.unit2)
        }
        let ret = await db.transaction(async () => {
            let invo = await invoice.save()
            if(invo) {
                infos.map(row => {
                    row.iid = invo.id
                    delete row.id
                })
            }
            if(id) {
                await db.models['invoiceInfo'].destroy({
                    where: {
                        tenantId,
                        iid: id
                    }
                })
            }
            await db.models['invoiceInfo'].bulkCreate(infos);
            await saveHistPrice(invo, infos)
            await setInvoiceGoods(tenantId, invo.id)

            let obj = Object.assign({}, invo)
            obj.infos = infos
            await tools.saveLogInvoice(tenantId, uid, invo.id, id ?'修改':'新增', obj);

            return invo
        })
        if(ret) {
            // let roomId = ctx.roomId
            // if(roomId) {
            //     setTimeout(async () => {
            //         let msg = '新增 手机订单'
            //         if(billId) msg = '手机订单 ' + invoice.billNo + ' 被修改'
            //         ctx.io.to(roomId).emit('appBillAdd', msg)
            //     }, 300)
            // }
        }

        return ctx.suc('提交成功', ret)
    } catch (e) {
        return ctx.err(e)
    }
})

module.exports = router;
